﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Linq.Expressions;
using System.Data.Metadata.Edm;

namespace EFong.Data
{
    public static class ObjectSetExtensions
    {
        public static int Delete<TEntity>(this ObjectSet<TEntity> objectSet, Expression<Func<TEntity, bool>> predicate)
            where TEntity : class
        {
            Type type = typeof(TEntity);
            EdmType edmType = objectSet.Context.MetadataWorkspace.GetType(type.Name, type.Namespace, DataSpace.OSpace);

            string tableName = edmType.Name;
            string command = String.Format("DELETE FROM [{0}]", tableName);

            ConditionBuilder conditionBuilder = new ConditionBuilder();
            conditionBuilder.Build(predicate.Body);

            if (!String.IsNullOrEmpty(conditionBuilder.Condition))
            {
                command += " WHERE " + conditionBuilder.Condition;
            }

            return objectSet.Context.ExecuteStoreCommand(command, conditionBuilder.Arguments);
        }

        //public static int Update<TEntity>(this Table<TEntity> table,
        //    Expression<Func<TEntity, TEntity>> evaluator, Expression<Func<TEntity, bool>> predicate)
        //    where TEntity : class
        //{
        //    return 0;
        //}
    }
}
